"use strict";

import { EventEmitter } from 'events';
import { JcDebugProcess } from "./JcDebugProcess";
import * as net from "net";

export class SocketComm extends EventEmitter {
    private sock: net.Socket;
    private ip: string;
    private port: number;
    public constructor() {
        super();

    }

    public connect(ip: string, port: number): net.Socket {
        this.sock = net.connect(port, ip);
        this.sock.on("close", (had_error: boolean) => this.onclose(had_error));
        this.sock.on("connect", () => this.onconnect());
        this.sock.on("data", (buffer: Buffer) => this.ondata(buffer));
        this.sock.on("end", () => this.onend());
        this.sock.on("error", (err: Error) => this.onerror(err));
        this.sock.on("timeout", () => this.ontimeout());
        return this.sock;
    }

    public disconnect() {
        this.sock.destroy();
    }

    public send(buffer: Buffer) {
        this.sock.write(buffer);
    }

    public onconnect() {
        this.emit("sockconnect");
    }
    public ondata(buffer: Buffer) {
        this.emit("sockdata", buffer);
    }
    public onclose(had_error: boolean) {
        this.emit("sockclose", had_error);
    }
    public onerror(err: Error) {
        this.emit("sockerror", err);
    }

    public onend() {
        this.emit("sockend");
    }

    public ontimeout() {
        this.emit("socktimeout");
    }
}





